﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Cashier_Interface;
using Cashier.utils;
using Cashier_Service;
using Cashier.pos;
using System.Collections;
using Cashier_Utils;
using Cashier_Model;

namespace Cashier.purchase
{
    public partial class PurchaseAddForm : Form, IGoodsNorm, IGoodsNumber
    {
        private MainForm mainform;
        private static PurchaseAddForm purchaseAddForm;
        private IReloadData iReloadData;
        private GoodsService goodsService;
        private BillPurchaseService purchaseService;
        private long goodsID;
        private bool isSaveSuccess = false;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="iReloadData"></param>
        private PurchaseAddForm(MainForm mainform, IReloadData iReloadData)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.iReloadData = iReloadData;
            this.goodsService = new GoodsService();
            this.purchaseService = new BillPurchaseService();

            Button[] buttons = { button_save };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);

            this.InitialDataGridViewColumns();
            this.comboBox_supplier.BindData();
            this.comboBox_category.BindData();
            this.textbox_purchaseno.Text = ToolsUtil.GeneratePurchaseNO();
            this.textbox_priceCost.LostFocus += new EventHandler(textbox_LostFocus);
            this.textbox_discount.LostFocus += new EventHandler(textbox_LostFocus);
            this.textbox_numbers.LostFocus += new EventHandler(textbox_LostFocus);
            this.textbox_priceDisc.LostFocus += new EventHandler(textbox_LostFocus);
        }

        /// <summary>
        /// 返回PurchaseAddForm实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="iReloadData"></param>
        /// <returns></returns>
        public static PurchaseAddForm GetPurchaseAddForm(MainForm mainform, IReloadData iReloadData)
        {
            if (purchaseAddForm == null)
                purchaseAddForm = new PurchaseAddForm(mainform, iReloadData);
            return purchaseAddForm;
        }

        #region 功能方法实现

        /// <summary>
        /// 定义DataGridView列
        /// </summary>
        private void InitialDataGridViewColumns()
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("barcode", "商品条码", true, 15, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_name", "商品名称", true, 19, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("category_name", "商品分类", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_norm", "商品规格", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_cost", "进货单价", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("discount", "折扣率", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_disc", "折后单价", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("numbers", "进货数量", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("total", "合计", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));            
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("note", "备注", true, 10, ActKey.LEFT, ActKey.LEFT, true, false));
        }

        /// <summary>
        /// 初始化商品数据
        /// </summary>
        /// <param name="row"></param>
        private void InitialGoodsData(DataRow row)
        {
            if (row != null)
            {
                this.goodsID = (long)row["id"];
                decimal price = (decimal)row["price_cost"];
                int numbers = 1;
                decimal discount = (decimal)row["discount"];
                this.textbox_goodsName.Text = row["name"].ToString();
                this.comboBox_category.Text = row["categoryname"].ToString();
                this.textbox_goodsNorm.Text = row["norm"].ToString();
                this.textbox_priceCost.Text = price.ToString();
                this.textbox_discount.Text = (discount > 0 ? discount : 1).ToString();
                this.textbox_priceDisc.Text = (price * discount).ToString();
                this.textbox_numbers.Text = numbers.ToString();
                this.textbox_total.Text = (price * discount * numbers).ToString();

                this.textbox_goodsName.Focus();
            }
        }

        /// <summary>
        /// 小品金额小计
        /// </summary>
        private void CountGoodsTotal()
        {
            try
            {
                decimal priceCost = textbox_priceCost.TextValueToDecimal;
                int numbers = textbox_numbers.TextValueToInt32;
                decimal discount = textbox_discount.TextValueToDecimal;
                decimal price_disc = priceCost * discount;
                decimal total = price_disc * numbers;
                textbox_priceDisc.Text = price_disc.ToString("f2");
                textbox_total.Text = total.ToString("f2");
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 添加商品数据行
        /// </summary>
        private void AddDataGridViewGoods()
        {
            try
            {
                bool isExist = false;
                decimal priceCost = textbox_priceCost.TextValueToDecimal;
                int numbers = textbox_numbers.TextValueToInt32;
                decimal discount = textbox_discount.TextValueToDecimal;
                decimal price_disc = priceCost * discount;
                decimal total = price_disc * numbers;

                String barcode = textbox_barcode.Text.Trim();
                String goodsNorm = textbox_goodsNorm.Text.Trim();
                foreach (DataGridViewRow lopRow in this.dataGridView1.Rows)
                {
                    if (barcode.Equals(lopRow.Cells["barcode"].Value.ToString()) && 
                        goodsNorm.Equals(lopRow.Cells["goods_norm"].Value.ToString()))
                    {
                        isExist = true;
                        int tempNumbers = (int)lopRow.Cells["numbers"].Value + numbers;
                        lopRow.Cells["price_cost"].Value = priceCost;
                        lopRow.Cells["discount"].Value = discount;
                        lopRow.Cells["price_disc"].Value = price_disc;
                        lopRow.Cells["numbers"].Value = tempNumbers;
                        lopRow.Cells["total"].Value = price_disc * tempNumbers;                       
                        break;
                    }
                }
                if (!isExist)
                {
                    int rowIndex = this.dataGridView1.Rows.Add();
                    this.dataGridView1.Rows[rowIndex].Cells["goods_id"].Value = this.goodsID;
                    this.dataGridView1.Rows[rowIndex].Cells["barcode"].Value = textbox_barcode.Text.Trim();
                    this.dataGridView1.Rows[rowIndex].Cells["goods_name"].Value = textbox_goodsName.Text.Trim();
                    this.dataGridView1.Rows[rowIndex].Cells["category_name"].Value = comboBox_category.Text;
                    this.dataGridView1.Rows[rowIndex].Cells["goods_norm"].Value = textbox_goodsNorm.Text.Trim();
                    this.dataGridView1.Rows[rowIndex].Cells["price_cost"].Value = priceCost;
                    this.dataGridView1.Rows[rowIndex].Cells["discount"].Value = discount;
                    this.dataGridView1.Rows[rowIndex].Cells["price_disc"].Value = price_disc;
                    this.dataGridView1.Rows[rowIndex].Cells["numbers"].Value = numbers;
                    this.dataGridView1.Rows[rowIndex].Cells["total"].Value = total;
                    this.dataGridView1.Rows[rowIndex].Cells["note"].Value = textbox_note.Text.Trim();
                }

                this.ClearGoodsInfo();
                this.PurchaseAccount();
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 清除商品数据
        /// </summary>
        private void ClearGoodsInfo()
        {
            this.goodsID = 0;
            textbox_barcode.Text = String.Empty;
            textbox_goodsName.Text = String.Empty;
            comboBox_category.SelectedIndex = 0;
            textbox_goodsNorm.Text = String.Empty;
            textbox_priceCost.Text = "0.00";
            textbox_discount.Text = "1.00";
            textbox_priceDisc.Text = "0.00";
            textbox_numbers.Text = "0";
            textbox_total.Text = "0.00";
            textbox_note.Text = String.Empty;

            textbox_barcode.Focus();
        }

        /// <summary>
        /// 进货单计算
        /// </summary>
        private void PurchaseAccount()
        {
            if (this.dataGridView1.Rows.Count > 0)
            {
                decimal goodsTotal = 0M;
                decimal purchaseTotal = 0M;
                int goodsNumber = 0;
                foreach (DataGridViewRow lopRow in this.dataGridView1.Rows)
                {
                    decimal priceCost = (decimal)lopRow.Cells["price_cost"].Value;
                    decimal priceDisc = (decimal)lopRow.Cells["price_disc"].Value;
                    int numbers = (int)lopRow.Cells["numbers"].Value;
                    goodsTotal += priceCost * numbers;
                    purchaseTotal += priceDisc * numbers;
                    goodsNumber += numbers;
                }
                label_numbers.Text = goodsNumber.ToString();
                label_goodsTotal.Text = goodsTotal.ToString("f2");
                textbox_purchaseTotal.Text = purchaseTotal.ToString("f2");
                textbox_discountTotal.Text = (goodsTotal - purchaseTotal).ToString("f2");
            }
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        protected void AddGoods()
        {
            ArrayList list = new ArrayList();
            FormUtil.GetValidateControlsNotPassed(this.panel2, list, 1);
            if (list.Count > 0)
                return;

            this.AddDataGridViewGoods();
        }

        /// <summary>
        /// 修改商品数量
        /// </summary>
        protected void UpdateGoodsNumbers()
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                DataGridViewRow row = this.dataGridView1.SelectedRows[0];
                int rowIndex = row.Index;
                String barcode = row.Cells["barcode"].Value.ToString();
                String goodsName = row.Cells["goods_name"].Value.ToString();
                String goodsNorm = row.Cells["goods_norm"].Value.ToString();
                int numbers = Int32.Parse(row.Cells["numbers"].Value.ToString());
                UpdateGoodsNumbersForm updateGoodsNumbersForm = new UpdateGoodsNumbersForm(this, rowIndex, barcode,
                    goodsName, goodsNorm, numbers, 0);
                updateGoodsNumbersForm.ShowDialog();
            }
        }

        /// <summary>
        /// 保存进货单
        /// </summary>
        protected void SavePurchase()
        {
            try
            {
                if (comboBox_supplier.SelectedIndex == 0)
                {
                    MessageBox.Show("请选择供应商！");
                    return;
                }
                decimal goodsTotal = Decimal.Parse(label_goodsTotal.Text);                
                decimal discountTotal = Decimal.Parse(textbox_discountTotal.Text.Trim());
                decimal fare = Decimal.Parse(textbox_fare.Text.Trim());
                decimal otherCost = Decimal.Parse(textbox_otherCost.Text.Trim());
                decimal purchaseTotal = Decimal.Parse(textbox_purchaseTotal.Text.Trim());
                decimal countTotal = purchaseTotal + fare + otherCost;                

                int goodsNumbers = 0;
                String purchaseno = textbox_purchaseno.Text.Trim();
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String storeNo = mainform.Admin.StoreNo;
                String adminUsername = mainform.Admin.Username;
                String adminName = mainform.Admin.Name;
                ArrayList list = new ArrayList();
                if (this.dataGridView1.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in this.dataGridView1.Rows)
                    {
                        BillPurchaseGoods goods = new BillPurchaseGoods();
                        goods.EnterpriseNo = enterpriseNo;
                        goods.StoreNo = storeNo;
                        goods.PurchaseNo = purchaseno;
                        goods.GoodsId = (long)row.Cells["goods_id"].Value;
                        goods.Barcode = row.Cells["barcode"].Value.ToString();
                        goods.CategoryName = row.Cells["category_name"].Value.ToString();
                        goods.GoodsName = row.Cells["goods_name"].Value.ToString();
                        goods.GoodsNorm = row.Cells["goods_norm"].Value.ToString();
                        goods.PriceCost = (decimal)row.Cells["price_cost"].Value;
                        goods.Discount = (decimal)row.Cells["discount"].Value;
                        goods.PriceDisc = (decimal)row.Cells["price_disc"].Value;
                        goods.Numbers = Int32.Parse(row.Cells["numbers"].Value.ToString());
                        goods.Total = (decimal)row.Cells["total"].Value;
                        goods.Note = row.Cells["note"].Value.ToString();
                        goods.AdminUsername = adminUsername;
                        goods.AdminName = adminName;
                        goods.Createtime = DateTime.Now;
                        list.Add(goods);
                        goodsNumbers += goods.Numbers;
                    }
                }

                if (goodsNumbers > 0)
                {
                    BillPurchase billPurchase = new BillPurchase();
                    billPurchase.EnterpriseNo = enterpriseNo;
                    billPurchase.StoreNo = storeNo;
                    billPurchase.PurchaseNo = purchaseno;
                    billPurchase.SupplierNo = comboBox_supplier.SelectedValue.ToString();
                    billPurchase.SupplierName = comboBox_supplier.Text;
                    billPurchase.Numbers = goodsNumbers;
                    billPurchase.GoodsTotal = goodsTotal;                   
                    billPurchase.DiscountTotal = discountTotal;
                    billPurchase.Fare = fare;
                    billPurchase.OtherCost = otherCost;
                    billPurchase.PurchaseTotal = purchaseTotal;
                    billPurchase.CountTotal = countTotal;
                    billPurchase.PurchaseDate = DateTime.Now;
                    billPurchase.Note = textbox_note.Text.Trim();
                    billPurchase.DebtAmount = countTotal;
                    billPurchase.AdminUsername = adminUsername;
                    billPurchase.AdminName = adminName;
                    billPurchase.Createtime = DateTime.Now;
                    long id = purchaseService.InsertBillPurchase(billPurchase, list);
                    if (id > 0)
                    {
                        isSaveSuccess = true;
                        DialogResult result = MessageBox.Show("创建成功，要继续创建吗？", "提示", MessageBoxButtons.YesNo);
                        if (result == DialogResult.Yes)
                        {
                            this.textbox_purchaseno.Text = ToolsUtil.GeneratePurchaseNO();
                            this.label_goodsTotal.Text = "0.00";
                            this.label_numbers.Text = "0";
                            this.textbox_purchaseTotal.Text = "0.00";
                            this.textbox_discountTotal.Text = "0.00";
                            this.textbox_note.Text = String.Empty;
                            this.ClearGoodsInfo();
                        }
                        else
                        {
                            this.Close();
                        }
                    }
                    else
                        MessageBox.Show("保存失败！");
                }
                else
                {
                    MessageBox.Show("没有任何商品！");
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        protected void DeletePurchaseGoods()
        {
            if (this.dataGridView1.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    this.dataGridView1.Rows.RemoveAt(row.Index);
                }
            }
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 输入商品条码事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_barcode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 13)
            {
                String barcode = this.textbox_barcode.Text.Trim();
                if (!String.IsNullOrEmpty(barcode.Trim()))
                {
                    DataTable dt = goodsService.GetGoodsTable(0, 0, barcode, null, 0, 0, null, 0, null, "id");
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        if (dt.Rows.Count > 1)
                        {
                            this.textbox_goodsName.Focus();
                            GoodsNormForm goodsNormForm = new GoodsNormForm(this, dt, "norm", "id");
                            goodsNormForm.ShowDialog();
                        }
                        else
                        {
                            this.InitialGoodsData(dt.Rows[0]);
                        }
                    }
                    else
                    {
                        MessageBox.Show("商品不存在！");
                    }
                }
            }
        }

        /// <summary>
        /// 失去焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_LostFocus(object sender, EventArgs e)
        {
            Cashier.usercontrols.TextboxExt textbox = (Cashier.usercontrols.TextboxExt)sender;
            if (String.IsNullOrEmpty(textbox.Text.Trim()))
            {
                if (textbox.Datatype == DataType.Money)
                    textbox.Text = "0.00";
                else if (textbox.Datatype == DataType.Integer || textbox.Datatype == DataType.Double ||
                    textbox.Datatype == DataType.Number)
                    textbox.Text = "0";
            }
            this.CountGoodsTotal();
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PurchaseAddForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            purchaseAddForm = null;
            if (iReloadData != null && isSaveSuccess)
            {
                iReloadData.ReloadDataGridViewData(null);
            }
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_addGoods_Click(object sender, EventArgs e)
        {
            this.AddGoods();
        }

        /// <summary>
        /// 修改商品数量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_updateGoodsNumber_Click(object sender, EventArgs e)
        {
            this.UpdateGoodsNumbers();
        }

        /// <summary>
        /// 保存进货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_save_Click(object sender, EventArgs e)
        {
            this.SavePurchase();
        }

        /// <summary>
        /// 删除进货商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_delete_Click(object sender, EventArgs e)
        {
            this.DeletePurchaseGoods();
        }

        #endregion

        #region IGoodsNorm 成员

        void IGoodsNorm.SelectGoodsNorm(object param)
        {
            if (param != null)
            {
                DataRow row = (DataRow)param;
                this.InitialGoodsData(row);
            }
        }

        #endregion


        #region IGoodsNumber 成员

        void IGoodsNumber.UpdateGoodsNumber(int rowIndex, string barcode, long goodsID, int numbers)
        {
            if (rowIndex < this.dataGridView1.Rows.Count)
            {
                DataGridViewRow row = this.dataGridView1.Rows[rowIndex];
                decimal priceDisc = (decimal)row.Cells["price_disc"].Value;
                row.Cells["numbers"].Value = numbers;
                row.Cells["total"].Value = priceDisc * numbers;
                this.PurchaseAccount();
            }
        }

        #endregion


        #region 方法重写

        /// <summary>
        /// 重写键盘事件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            switch (keyData)
            {
                case Keys.F5:
                    this.SavePurchase();
                    break;
                case Keys.F6:
                    this.UpdateGoodsNumbers();
                    break;
                case Keys.Add:
                    b = true;
                    this.AddGoods();
                    break;
                case Keys.Oemplus:
                    b = true;
                    this.AddGoods();
                    break;
                case Keys.Delete:
                    this.DeletePurchaseGoods();
                    break;
            }
            return b;
        }

        #endregion

    }
}
